import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useReducer, useEffect } from "react";
import { Alert, Keyboard } from "react-native";
import queryApi from "../../api/query";

const companyInfoContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "initCompanyInfo":
      return action.payload;
    case "editCompanyInfo":
      return action.payload;
    default:
      return state;
  }
};

export const CompanyInfoProvider = ({ children }) => {
  const [companyInfo, dispatch] = useReducer(dataReducer, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = await AsyncStorage.getItem("token");
        if (!token) {
          console.log("请求userId出错");
        }
        const result = await queryApi.get("/company/usercompanyinfo", {
          headers: { Authorization: token },
        });
        if (result.data.message) {
          dispatch({ type: "initCompanyInfo", payload: result.data.message });
        }
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

  const editCompanyInfo = async (updateData) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const result = await queryApi.post(
        "/company/usercompanyinfo",
        updateData,
        {
          headers: { Authorization: token },
        }
      );
      if (result.data.status == "success") {
        dispatch({
          type: "editCompanyInfo",
          payload: result.data.companyInfo,
        });
        Keyboard.dismiss();
        Alert.alert("成功", "编译信息成功", [{ text: "确定" }]);
      } else {
        Alert.alert("失败", "编译信息出错", [{ text: "确定" }]);
      }
    } catch (err) {
      console.log("修改公司信息出错", err);
    }
  };

  return (
    <companyInfoContext.Provider
      value={{
        companyInfo: companyInfo,
        editCompanyInfo,
      }}
    >
      {children}
    </companyInfoContext.Provider>
  );
};

export default companyInfoContext;
